import qs from '../libs/qs.js';
import axios from '../libs/axios.min.js';

class Ajax {
  // 构造函数和传入的初始化参数
  constructor(baseUrl, tokenKey) {
    this.baseUrl = baseUrl;
    this.tokenKey = tokenKey;
    console.log('服务器参数：', this.baseUrl, this.tokenKey);
  }

  saveToken(data) {
    if (data && data.token) {
      localStorage.setItem(this.tokenKey, data.token);
    }
  }

  loadToken() {
    let token = localStorage.getItem(this.tokenKey);
    return token ? token : '';
  }

  send(url, params, callback, method) {
    let reqdata = qs.stringify(params, { allowDots: true });
    // get请求是地址栏处理
    if ('GET' == method.toUpperCase()) {
      url = `${this.baseUrl}${url}?${reqdata}`;
      reqdata = '';
    } else {
      url = this.baseUrl + url;
    }
    let instance = this;
    console.log('this对象：', this, instance);
    // axios请求
    let promise = axios({
      url: url,
      data: reqdata,
      method: method,
      headers: {
        token: instance.loadToken(),
      },
    });
    promise
      .then((resp) => {
        console.log('应答结果：', resp);
        console.log('this对象：', this, instance);
        instance.saveToken(resp.data);
        callback(resp.data);
      })
      .catch((err) => {
        console.error('请求发生错误', err);
        callback({
          code: 500,
          success: false,
          message: '请求失败，请稍后重试',
        });
      });
    // servlet filter listener
  }
}

export default Ajax;
export { Ajax as Ajax };

// typescript
